# -*- encoding: utf-8 -*-

"""
@File:      tc_lmdb_lmdb_func_001.py
@Time:      2024/03/27 14:33:20
@Author:    chenchunhu
@Version:   1.0
@Contact:   wb-cch358909@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    chenchunhu
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_lmdb_lmdb_func_001.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """

    PARAM_DIC = {"pkg_name": "lmdb lmdb-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = '''cat >lmdb_test1.c<<"EOF"
#include <stdio.h>
#include <stdlib.h>
#include "lmdb.h"

#define E(expr) CHECK((rc = (expr)) == MDB_SUCCESS, #expr)
#define CHECK(test, msg) ((test) ? (void)0 : ((void)fprintf(stderr, "%s:%d: %s: %s\\n", __FILE__, __LINE__, msg, mdb_strerror(rc)), abort()))

int main(int argc, char * argv[]) {
    int rc;
    MDB_env *env;
    MDB_dbi dbi;
    MDB_val key, data;
    MDB_txn *txn;
    char sval[32];

    // 设置LMDB环境
    E(mdb_env_create(&env));
    E(mdb_env_open(env, "./lmdb_test1_db", 0, 0664));

    // 开启事务
    E(mdb_txn_begin(env, NULL, 0, &txn));
    E(mdb_dbi_open(txn, NULL, 0, &dbi));

    // 设置key-value对，然后提交事务
    key.mv_size = sizeof(int);
    key.mv_data = sval;
    data.mv_size = sizeof(sval);
    data.mv_data = sval;

    sprintf(sval, "%03x %d foo bar", 32, 3141592);
    E(mdb_put(txn, dbi, &key, &data, 0));
    E(mdb_txn_commit(txn));

    // 开启新的读取事务并获取数据
    E(mdb_txn_begin(env, NULL, MDB_RDONLY, &txn));
    E(mdb_get(txn, dbi, &key, &data));
    printf("got data: %.*s\\n", (int) data.mv_size, (char *) data.mv_data);

    // 清理
    mdb_dbi_close(env, dbi);
    mdb_env_close(env);
    
    return 0;
}
EOF'''
        self.cmd(cmdline)
        self.cmd("mkdir -p lmdb_test1_db")


    def test(self):
        self.cmd("gcc lmdb_test1.c -o lmdb_test1 -llmdb")
        code, lmdb_result = self.cmd("./lmdb_test1")
        self.assertIn("got data: 020 3141592 foo bar", lmdb_result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf lmdb_test1.c lmdb_test1 lmdb_test1_db")
